import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
export const usePlayerStore = defineStore("player", videoKey => {
  const isPlayerEnd = ref(false);
  const isPlayerReady = ref(false);
  const playerStorageKey = ref("");
  const maxProgress = ref(0);
  const initProgress = ref(0);
  const isControlsEnabled = ref(false);
  const isKeyboardVisible = ref(false);
  const setPlayerStorageKey = (key: string) => {
    playerStorageKey.value = key;
    // 设置 key 后重新读取进度
    initProgress.value = parseFloat(localStorage.getItem(key) || "0");
  };
  // 是否全屏
  const isFullScreen = ref(false);
  const setFullScreen = (fullScreen: boolean) => {
    isFullScreen.value = fullScreen;
  };
  const setInitProgress = (progress: number) => {
    initProgress.value = progress;
  };
  const setKeyboardVisible = (visible: boolean) => {
    isKeyboardVisible.value = visible;
  };
  const updateMaxProgress = (progress: number) => {
    maxProgress.value = progress;
  };
  const setPlayerEnd = () => {
    isPlayerEnd.value = true;
  };
  const setPlayerStart = () => {
    isPlayerEnd.value = false;
  };
  const setPlayerReady = (progress: number) => {
    isPlayerReady.value = true;
    initProgress.value = progress;
  };
  const setControlsEnabled = (enabled: boolean) => {
    isControlsEnabled.value = enabled;
  };
  if (import.meta.env.VITE_VIDEO_DEBUG) {
    // setControlsEnabled(true);
  }
  const realProgress = computed(() => maxProgress.value + initProgress.value);
  watch(realProgress, newProgress => {
    if (playerStorageKey.value) {
      localStorage.setItem(playerStorageKey.value, newProgress.toString());
    }
  });
  return {
    initProgress,
    maxProgress,
    isPlayerEnd,
    isPlayerReady,
    updateMaxProgress,
    setPlayerEnd,
    setPlayerReady,
    isControlsEnabled,
    setControlsEnabled,
    isKeyboardVisible,
    setKeyboardVisible,
    isFullScreen,
    setFullScreen,
    playerStorageKey,
    setPlayerStorageKey,
    setInitProgress,
    realProgress,
    setPlayerStart
  };
});
export type PlayerStore = ReturnType<typeof usePlayerStore>;
